package top.zhangjianyong.utils;

import org.bytedeco.javacpp.avcodec;
import org.bytedeco.javacv.*;

import java.io.File;

/**
 * 视频转码工具类
 */
public class VideoConvertUtil {

    public static void convert(File file, String output) throws Exception {
        //FFmpegFrameGrabber grabber = FFmpegFrameGrabber.createDefault(file.getAbsolutePath());
        FFmpegFrameGrabber grabber = new FFmpegFrameGrabber(file);

        Frame captured_frame;
        FFmpegFrameRecorder recorder = null;

        try {
            grabber.start();
            String savePath =output+File.separator+file.getName()+".mp4";
            recorder = new FFmpegFrameRecorder(savePath, grabber.getImageWidth(), grabber.getImageHeight(), grabber.getAudioChannels());
            recorder.setVideoCodec(avcodec.AV_CODEC_ID_H264);
            recorder.setFormat("mp4");
            recorder.setFrameRate(grabber.getFrameRate());
            recorder.setSampleRate(grabber.getSampleRate());
            recorder.setVideoBitrate(grabber.getVideoBitrate());
            recorder.setAspectRatio(grabber.getAspectRatio());
            recorder.setAudioBitrate(grabber.getAudioBitrate());
            recorder.setAudioOptions(grabber.getAudioOptions());
            recorder.setAudioCodec(avcodec.AV_CODEC_ID_AAC);
            recorder.start();

            while (true) {
                captured_frame = grabber.grabFrame();
                if (captured_frame == null) {
                    System.out.println("转码完成");
                    break;
                }
                recorder.record(captured_frame);
            }

        } catch (FrameRecorder.Exception e) {
            e.printStackTrace();
        } finally {
            if (recorder != null) {
                try {
                    recorder.close();
                } catch (Exception e) {
                    System.out.println("recorder.close异常" + e);
                }
            }

            try {
                grabber.close();
            } catch (FrameGrabber.Exception e) {
                System.out.println("frameGrabber.close异常" + e);
            }
        }
    }

    public static void main(String[] args) throws Exception {
        String savePath="/Users/zhangjianyong/Downloads/output/";
        String file = "/Users/zhangjianyong/Downloads/video_file/video/P220616_221025_222025.264";
        convert(new File(file),savePath);
    }
}
